import { isFillYearBeforeLast, waitTimeOut } from '../../common.js'
import { CWBB_JSON, CWBB_MONTH_JSON } from '../data/cwbb-json.js'
import { fillInputDone, notifications } from "../../message.js"

/**
 * 转换财务报表数据
 * @param {*} sheet 表类型-资产负债表、利润表、现金流量表
 * @param {*} type 会计准则类型
 * @param {*} saasData 系统数据
 * @param {*} baseInfoCache 账套数据
 */
function transformCwbbData(sheet, type, saasData, baseInfoCache) {
  // 测试用
  // baseInfoCache = {
  //   companyInfo: {
  //     startDate: '2021-12'
  //   }
  // }
  // 根据表类型和会计准则类型确定转换json
  const transformJson = CWBB_JSON[sheet][type]
  let inputData = {}
  if (sheet === 'balance') {
    inputData = transformBalance(saasData, transformJson)
  } else if (sheet === 'profit') {
    inputData = transformProfit(saasData, transformJson, baseInfoCache)
  } else if (sheet === 'cash') {
    inputData = transformCash(saasData, transformJson, baseInfoCache)
  }
  return inputData
}

function transformCash(saasData, transformJson, baseInfoCache) {
  const nowCash = saasData.data.openParams.inputData.data.cash
  const lastCash = saasData.data.openParams.inputData.lastYearData.cash
  const transformJsonNowCash = transformJson.now
  const transformJsonLastCash = transformJson.last
  let result = {}
  for (let key in transformJsonNowCash) {
    const item = nowCash.filter(item => item.reportItemUuid === transformJsonNowCash[key]['uuid'])
    if (item.length) {
      result[key] = item[0][transformJsonNowCash[key]['value']] ? Number(item[0][transformJsonNowCash[key]['value']]) : 0
    }
  }
  if (isFillYearBeforeLast(baseInfoCache)) {
    for (let key in transformJsonLastCash) {
      const item = lastCash.filter(item => item.reportItemUuid === transformJsonLastCash[key]['uuid'])
      if (item.length) {
        result[key] = item[0][transformJsonLastCash[key]['value']] ? Number(item[0][transformJsonLastCash[key]['value']]) : 0
      }
    }
  }
  return result
}

function transformProfit(saasData, transformJson, baseInfoCache) {
  const nowProfit = saasData.data.openParams.inputData.data.profit
  const lastProfit = saasData.data.openParams.inputData.lastYearData.profit
  const transformJsonNowProfit = transformJson.now
  const transformJsonLastProfit = transformJson.last
  let result = {}
  for (let key in transformJsonNowProfit) {
    const item = nowProfit.filter(item => item.reportItemUuid === transformJsonNowProfit[key]['uuid'])
    if (item.length) {
      result[key] = item[0][transformJsonNowProfit[key]['value']] ? Number(item[0][transformJsonNowProfit[key]['value']]) : 0
    }
  }
  if (isFillYearBeforeLast(baseInfoCache)) {
    for (let key in transformJsonLastProfit) {
      const item = lastProfit.filter(item => item.reportItemUuid === transformJsonLastProfit[key]['uuid'])
      if (item.length) {
        result[key] = item[0][transformJsonLastProfit[key]['value']] ? Number(item[0][transformJsonLastProfit[key]['value']]) : 0
      }
    }
  }
  return result
}

function transformBalance(saasData, transformJson) {
  const { balance } = saasData.data.openParams.inputData.data
  let result = {}
  for (let key in transformJson) {
    const item = balance.filter(item => item.reportItemUuid === transformJson[key]['uuid'])
    if (item.length) {
      result[key] = item[0][transformJson[key]['value']] ? Number(item[0][transformJson[key]['value']]) : 0
    }
  }
  return result
}
// 公司名称：上饶市旦旦建材有限公司 税号：91361100MA7JECD09P 密码：yh7891234 办税人  手机号码：18907931347
async function cwbbInput(sheet, type, saasData, baseInfoCache) {
  if (saasData.isYearReport) {
    const inputData = transformCwbbData(sheet, type, saasData, baseInfoCache)
    await fillInput(inputData)
  } else {
    const inputData = transformCwbbData_Month(saasData, baseInfoCache)
    await fillInput(inputData)
  }

}

function transformCwbbData_Month(saasData, baseInfoCache) {
  const sheet = saasData.sheet;
  const ins = baseInfoCache.companyInfo.institutionCode === '2' ? 'xqykjzz' : 'qykjzz';
  if (ins !== 'xqykjzz') throw new Error('未支持的会计准则');
  const inputData = saasData.data.openParams.inputData.data[sheet];
  const vk = CWBB_MONTH_JSON[ins][sheet];
  let obj = {};
  for (let k in vk) {
    let v = vk[k];
    v = v.replace('h', '');
    let saasItem = inputData[v];
    if (sheet === 'balance') {
      if (k.includes('qmye')) { // 期末余额
        obj[k] = saasItem.colValue1;
      }
      if (k.includes('ncye')) { // 期末余额
        obj[k] = saasItem.colValue2;
      }
    } else if (sheet === 'profit') {
      if (k.includes('lrbnlj')) { // 本年累计金额
        obj[k] = saasItem.colValue1;
      }
      if (k.includes('lrbyje')) { // 本期金额
        obj[k] = saasItem.colValue2;
      }
    } else if (sheet === 'cash') {
      if (k.includes('xjbnlj')) { // 本年累计金额
        obj[k] = saasItem.colValue1;
      }
      if (k.includes('xjbyje')) { // 本期金额
        obj[k] = saasItem.colValue2;
      }
    }
  }
  return obj;
}

function trigger(DOM) {
  let event = document.createEvent("MouseEvents");
  event.initEvent("blur", true, true);
  DOM.dispatchEvent(event);
}

function tiggerDom(array) {
  for (let i = 0; i < array.length; i++) {
    let dom = document.querySelector(`#${array[i]}`);
    if (dom) {
      trigger(dom);
    }
  }
}

async function fillInput(inputData) {
  let message = '填报成功'
  try {
    for (let key in inputData) {
      let value = inputData[key] ? Number.parseFloat(inputData[key]).toFixed(2) || "0.00" : '0.00';
      // let value = Number.parseFloat(inputData[key]).toFixed(2);
      let formVal = eval("document.querySelector('#" + key + "')");
      let tdVal = formVal ? eval("document.querySelector('#" + key + "')") : "undefined";

      if (tdVal !== "undefined") {
        eval("document.querySelector('#" + key + "').value=" + value);
      }
    }

    // 触发blur
    let domArray = Object.keys(inputData);
    tiggerDom(domArray);
  } catch (e) {
    message = "填报失败,请反馈技术人员！" + e;
  }

  await waitTimeOut(1500)
  fillInputDone({
    message: message,
  })
}

export {
  cwbbInput
}